//
//  MYHTTPManager.m
//  JQLive
//
//  Created by Bruce on 2019/11/28.
//  Copyright © 2019 mlqk. All rights reserved.
//

#import "MYHTTPManager.h"
#import "MYHttpClient.h"

@implementation MYHTTPManager
+ (void)monitoringNetworkState:(void (^)(NSInteger))block{
    
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    [manager startMonitoring];
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusUnknown:
            {
                //未知网络
                DLog(@"[网络状态切换]--未知网络");
            }
                break;
            case AFNetworkReachabilityStatusNotReachable:
            {
                //无法联网
                DLog(@"[网络状态切换]--无法联网");
            }
                break;
                
            case AFNetworkReachabilityStatusReachableViaWWAN:
            {
                //手机自带网络
                DLog(@"[网络状态切换]--当前使用的是2g/3g/4g网络");
            }
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi:
            {
                //WIFI
                DLog(@"[网络状态切换]--当前在WIFI网络下");
            }
                
        }
        block(status);
    }];
}
#pragma mark 普通一般的网络请求

/**
 封装AFN POST请求
 
 @param urlString 请求链接
 @param parameters 请求参数
 @param successHandle 请求成功回调
 @param failureHandle 请求失败回调
 */
+ (void)postAFNWithUrl:(NSString *)urlString
            parameters:(id)parameters
MYServiceModuleType:(MYServiceModuleType)MYServiceModuleType
         successHandle:(void(^)(NSURLSessionTask *task, id response))successHandle
         failureHandle:(void(^)(NSURLSessionTask *task, NSError *error))failureHandle
{
    MYHttpClient *httpClinet;
    
    switch (MYServiceModuleType) {
        case PublicBaseUrl_Type:
            httpClinet = [MYHttpClient sharedPublicManager];
            break;
    }
   
    [self setAuthorization:httpClinet withUrlStr:urlString];

    
    [httpClinet.requestSerializer setValue:@"application/x-www-form-urlencoded; charset=UTF-8" forHTTPHeaderField:@"Content-Type"];

    DLog(@"\nurl:%@%@\nparam:%@",httpClinet.baseURL.absoluteString, urlString,parameters);
    [MYTipUtils showLoading];
    [httpClinet POST:urlString parameters:parameters  progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [MYTipUtils hideAllTips];
        NSDictionary *dict =  [JQLiveTools dictionaryWithData:responseObject];
//
        successHandle(task,dict);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [MYTipUtils hideAllTips];
        failureHandle(task,error);

    }];
}

/**
 封装AFN GET请求
 
 @param urlString 请求链接
 @param parameters 请求参数
 @param successHandle 请求成功回调
 @param failureHandle 请求失败回调
 */
+ (void)getAFNWithUrl:(NSString *)urlString
           parameters:(id)parameters
MYServiceModuleType:(MYServiceModuleType)MYServiceModuleType
        successHandle:(void(^)(NSURLSessionTask *task, id response))successHandle
        failureHandle:(void(^)(NSURLSessionTask *task, NSError *error))failureHandle
{
   
    
    MYHttpClient *httpClinet;
    switch (MYServiceModuleType) {
        case PublicBaseUrl_Type:
        httpClinet = [MYHttpClient sharedPublicManager];
        break;
    }
    [self setAuthorization:httpClinet withUrlStr:urlString];

    //响应对象
   
    [httpClinet.requestSerializer setValue:@"application/x-www-form-urlencoded; charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
    
    DLog(@"\nurl:%@%@\nparam:%@",httpClinet.baseURL.absoluteString, urlString,parameters);
    [MYTipUtils showLoading];
    [httpClinet GET:urlString parameters:parameters  progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [MYTipUtils hideAllTips];
        NSDictionary *dict =  [JQLiveTools dictionaryWithData:responseObject];
        successHandle(task,dict);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
//        NSInteger codeint = error.code;
//        if (codeint == (-999)) {
//            DLog(@"网络状态输出====>>> 网络请求已取消");
//        }
//        else if(codeint == (-1001)){
//            DLog(@"网络状态输出====>>> 网络请求超时");
//        }
//        else if (codeint == (401))
//        {
//            [MYTipUtils showAlertString:@"请求授权连接失败"];
//
//        }
//        else {
//             [MYTipUtils showAlertString:@"网络请求失败"];
//        }
//
        //错误的值域(NSURLErrorDomain)
        [MYTipUtils hideAllTips];
        NSLog(@"error.domain：%@",error.domain);
        //错误信息
        NSLog(@"error.description：%@",error.description);
        //错误状态的本地化描述
        NSLog(@"localizedDescription：%@", [error localizedDescription]);
        failureHandle(task,error);

    }];
}
/**
 封装AFN DELETE请求
 
 @param urlString 请求链接
 @param parameters 请求参数
 @param successHandle 请求成功回调
 @param failureHandle 请求失败回调
 */
+ (void)deleteAFNWithUrl:(NSString *)urlString
            parameters:(id)parameters
MYServiceModuleType:(MYServiceModuleType)MYServiceModuleType
         successHandle:(void(^)(NSURLSessionTask *task, id response))successHandle
         failureHandle:(void(^)(NSURLSessionTask *task, NSError *error))failureHandle
{
    MYHttpClient *httpClinet;
    switch (MYServiceModuleType) {
       case PublicBaseUrl_Type:
       httpClinet = [MYHttpClient sharedPublicManager];
       break;
    }
    
   [self setAuthorization:httpClinet withUrlStr:urlString];

    [httpClinet.requestSerializer setValue:@"application/x-www-form-urlencoded; charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
    
    DLog(@"\nurl:%@%@\nparam:%@",httpClinet.baseURL.absoluteString, urlString,parameters);
    [MYTipUtils showLoading];
    [httpClinet DELETE:urlString parameters:parameters  success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [MYTipUtils hideAllTips];
        NSDictionary *dict =  [JQLiveTools dictionaryWithData:responseObject];

        successHandle(task,dict);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [MYTipUtils hideAllTips];
        failureHandle(task,error);
    }];
    
}
/**
 封装AFN PUT请求
 
 @param urlString 请求链接
 @param parameters 请求参数
 @param successHandle 请求成功回调
 @param failureHandle 请求失败回调
 */
+ (void)putAFNWithUrl:(NSString *)urlString
            parameters:(id)parameters
MYServiceModuleType:(MYServiceModuleType)MYServiceModuleType
         successHandle:(void(^)(NSURLSessionTask *task, id response))successHandle
         failureHandle:(void(^)(NSURLSessionTask *task, NSError *error))failureHandle
{
    MYHttpClient *httpClinet;
    switch (MYServiceModuleType) {
        case PublicBaseUrl_Type:
        httpClinet = [MYHttpClient sharedPublicManager];
        break;
    }
    [self setAuthorization:httpClinet withUrlStr:urlString];

   
    [httpClinet.requestSerializer setValue:@"application/x-www-form-urlencoded; charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
    
    DLog(@"\nurl:%@%@\nparam:%@",httpClinet.baseURL.absoluteString, urlString,parameters);
    [MYTipUtils showLoading];
    [httpClinet PUT:urlString parameters:parameters  success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [MYTipUtils hideAllTips];
        NSDictionary *dict =  [JQLiveTools dictionaryWithData:responseObject];

        successHandle(task,dict);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [MYTipUtils hideAllTips];
        failureHandle(task,error);
    }];
    
}
/**
 *  上传文件
 *
 *  @param urlString      url地址
 *  @param params         params参数
 *  @param mimeType         mimeType参数
 *

 @param successHandle 请求成功回调
 @param failureHandle 请求失败回调
 */
+ (void)requestDataWithURL:(NSString *)urlString
                withParams:(NSMutableDictionary *)params
                  withData:(NSData *)fileData
              withDataName:(NSString *)dataName
              withFileName:(NSString *)fileName
                  mimeType:(NSString *)mimeType
                  progress:(nullable void (^)(NSProgress * _Nonnull uploadProgress))uploadProgressZSP
             successHandle:(void(^)(NSURLSessionTask *task, id response))successHandle
             failureHandle:(void(^)(NSURLSessionTask *task, NSError *error))failureHandle
{
    if (params == nil) {
        params = [NSMutableDictionary dictionary];
    }
    
    MYHttpClient *httpClinet = [MYHttpClient sharedPublicManager];
    
   [self setAuthorization:httpClinet withUrlStr:urlString];

    [httpClinet.requestSerializer setValue:@"application/x-www-form-urlencoded; charset=UTF-8;multipart/form-data" forHTTPHeaderField:@"Content-Type"];

    DLog(@"\nurl:%@%@\nparam:%@",httpClinet.baseURL.absoluteString, urlString,params);
    [MYTipUtils showLoading];
    [httpClinet POST:urlString parameters:params   constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFileData:fileData name:dataName fileName:fileName mimeType:mimeType];
        

    } progress:^(NSProgress * _Nonnull uploadProgress) {
        uploadProgressZSP(uploadProgress);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [MYTipUtils hideAllTips];
          NSDictionary *dict =  [JQLiveTools dictionaryWithData:responseObject];
//
        successHandle(task,dict);

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [MYTipUtils hideAllTips];
        failureHandle(task,error);

    }];
   
}
/**
 *  多文件上传
 *
 *  @param dataArray      url地址
 *

 @param successHandle 请求成功回调
 @param failureHandle 请求失败回调
 */
+ (void)requestDataWithArray:(NSMutableArray *)dataArray
                  progress:(nullable void (^)(NSProgress * _Nonnull uploadProgress))uploadProgressZSP
             successHandle:(void(^)(NSURLSessionTask *task, id response))successHandle
             failureHandle:(void(^)(NSURLSessionTask *task, NSError *error))failureHandle
{
  
        
        MYHttpClient *httpClinet = [MYHttpClient sharedPublicManager];
        
    [self setAuthorization:httpClinet withUrlStr:nil];
    
        [httpClinet.requestSerializer setValue:@"application/x-www-form-urlencoded; charset=UTF-8;multipart/form-data" forHTTPHeaderField:@"Content-Type"];

        DLog(@"\nurl:%@%@\n",httpClinet.baseURL.absoluteString, @"xxx");
        [MYTipUtils showLoading];
        [httpClinet POST:@"xxxx" parameters:nil   constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
            for (int i = 0; i <dataArray.count; i ++)
            {
                NSDictionary *dict = dataArray[i];
                NSData *fileData = dict[@"fileData"];
                NSString *dataName = dict[@"dataName"];
                NSString *fileName = dict[@"fileName"];
                NSString *mimeType = dict[@"mimeType"];

                [formData appendPartWithFileData:fileData name:dataName fileName:fileName mimeType:mimeType];

            }

        } progress:^(NSProgress * _Nonnull uploadProgress) {
            uploadProgressZSP(uploadProgress);
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            [MYTipUtils hideAllTips];
              NSDictionary *dict =  [JQLiveTools dictionaryWithData:responseObject];
    //
            successHandle(task,dict);

        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            [MYTipUtils hideAllTips];
            failureHandle(task,error);

        }];
}
+ (NSString *)getHttpSignWithParams:(NSMutableDictionary *)params withTime:(NSString *)time
{
    NSString *sign = @"";
    
    return sign;
}

+ (void)setAuthorization:(MYHttpClient *)httpClinet withUrlStr:(NSString *)url
{
//    [MYAccountManager sharedManager].memberId;
    MYUserModel *model = [[MYAccountManager sharedManager] accountModel];
//    NSString *tokenType = @"Bearer";
  
    NSString *accessToken = model.accessToken.accessToken;
    
    DLog(@"accessToken：  %@", accessToken);
    if(accessToken){
        [httpClinet.requestSerializer setValue:[NSString stringWithFormat:@"%@", accessToken] forHTTPHeaderField:@"Authorization"];
    }else{
        [httpClinet.requestSerializer setValue:[NSString stringWithFormat:@""] forHTTPHeaderField:@"Authorization"];
    }
}
@end
